package com.ll.hangertv;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.ll.hangertv.javascriptInterface.MyJavascriptInterface;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {
    static  String TAG = "MainActivity";
    public Context context;
    public static String url = "";
    private WebView webView;
    public TimerHandler timerhandler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        context = this.getApplicationContext();
        initWebView();
        try
        {
            if(URLUtil.isHttpUrl(SplashActivity.url)||URLUtil.isHttpsUrl(SplashActivity.url)) {
                webView.loadUrl(SplashActivity.url);
                url = SplashActivity.url;
            }
            else
            {
                Toast.makeText(MainActivity.this, "url is not valid....", Toast.LENGTH_SHORT).show();
            }
            timer.schedule(task, 1000, 3000); //定时获取网络状态
            timerhandler = new TimerHandler();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
        }
    }


    private void initWebView()
    {

        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);// 打开本地缓存提供JS调用,至关重要
        webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 12);// 实现8倍缓存
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);

        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
       // webView.getSettings().setSupportZoom(true);
       // webView.getSettings().setBuiltInZoomControls(true);
        //webView.setInitialScale(100);
        //webView.getSettings().setDefaultFontSize(15);
        String appCachePath = getApplication().getCacheDir().getAbsolutePath();
        // String appCachePath = Config.webViewCachePath;


        webView.getSettings().setAppCachePath(appCachePath);
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);


        //优先使用缓存
        //webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

        //添加javaScript接口
        MyJavascriptInterface tmp = new MyJavascriptInterface(timerhandler,context);
         webView.addJavascriptInterface(tmp, "mobile");

        // final String serverIp = "http://192.168.100.72:3000/";
        //String serverIp = "http://"+Config.devConfig.web_addr;
        //String serverIp = "http://"+"192.168.100.99:8888/rest/core/show/tv";

        // String serverIp = "http://192.168.100.99:8888/admin/login";
        //String serverIp = "http://192.168.100.99:8888/admin/login";

        //  String serverIp = "https://www.163.com/";


        webView.setWebViewClient(new WebViewClient()
        {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon)
            {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url)
            {
                super.onPageFinished(view, url);
            }

            @Override
            public void onLoadResource(WebView view, String url)
            {
                // Log.i(TAG, "onLoadResource url="+url);
                super.onLoadResource(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView webview, String url)
            {
                webview.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
            {


            }
        });
/*        tmp.writeSomeFile("cookies","fuck");
        String s = tmp.readSomeFile("cookies");
        Log.i(TAG,s);*/

 /*       String path ;
        path = "";
        Log.i(TAG,serverIp);
        String url = serverIp + path */;

    }

    //判断网络是否正常
    public boolean isNetworkConnected(Context context)
    {
        if (context != null)
        {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    private int timeOut0 = 0;
    private int timeOut1 = 0;

    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run()
        {

            if(!isNetworkConnected(context))
            {
                timeOut0++;
                if(timeOut0 > 2) //15s
                {
                    Message message = new Message();
                    message.arg1 = 100;
                    timerhandler.sendMessage(message);
                    timeOut0 = 0;
                }
            }
            else
            {
                timeOut1++;
                if(timeOut1 > 2) //10s
                {
                    Message message = new Message();
                    message.arg1 = 101;
                    timerhandler.sendMessage(message);
                    timeOut1 = 0;
                }
            }
        }
    };

    private static  int stateFlag = 0;

    private static  int openUrl = 0;

    class TimerHandler extends Handler {
        @Override
        //接收别的线程的信息并处理
        public void handleMessage(Message msg)
        {
            if(isFinishing())
            {
                return;
            }
            try
            {
                switch (msg.arg1)
                {
                    case 100:
                    {
                        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");// HH:mm:ss//获取当前时间
                       // Date date = new Date(System.currentTimeMillis());
                       // String time = simpleDateFormat.format(date);
                        Toast.makeText(MainActivity.this, getString(R.string.netError), Toast.LENGTH_SHORT).show();
                        stateFlag = 1;
                        openUrl = 1;
                    }break;
                    case 101:
                    {

                        stateFlag = 0 ;
                        if(stateFlag == 0 && openUrl == 1)
                        {
                            openUrl = 0;
                            webView.loadUrl(url);
                        }
                    }
                    break;
                    default:
                        break;

                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

}
